package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"gosecond/ch16grpc/streamgrpc/proto"
	"sync"
	"time"
)

func main() {
	conn, err := grpc.Dial("127.0.0.1:50052", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	cli := proto.NewGreeterClient(conn)

	//服务端流模式
	fmt.Println("服务端流模式: ")
	res, _ := cli.GetStream(context.Background(), &proto.StreamReqData{Data: "慕课网"})
	for {
		a, err := res.Recv() //socket变成。send recv
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(a.Data)
	}

	//客户端流模式
	fmt.Println("客户端流模式: ")
	putS, _ := cli.PutStream(context.Background())
	i := 0
	for {
		i++
		_ = putS.Send(&proto.StreamReqData{
			Data: fmt.Sprintf("慕课网：%d", i),
		})
		time.Sleep(time.Second)

		if i>10{
			break
		}
	}

	//双向流模式
	fmt.Println("双向流模式: ")
	allStr, _:=cli.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	//接受数据
	go func() {
		defer wg.Done()
		for {
			data, _ := allStr.Recv()
			fmt.Println("收到服务端消息：", data.Data)
		}
	}()

	//发送数据
	go func() {
		defer wg.Done()
		for {
			_ = allStr.Send(&proto.StreamReqData{
				Data: "我是客户端",
			})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()
}
